﻿using RentHouse.Service.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RentHouse.Admin.App_Start
{
    public class MyAuthorizationFilterAttribute:ActionFilterAttribute
    {
        DBModel _dbModel = new DBModel();


        //在执行Action之前，进行权限验证
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
            //token 的值为（"token=xxx"）需要进行字符串操作Split（'='）[1],根据=分割，取出token值
            string token = request.Headers["Authorization"];
            
            T_AdminUsers user = null;

            //验证token
            if (token != null) {
                token = token.Split('=')[1];
                user = _dbModel.T_AdminUsers.Where(u => u.Name == token).FirstOrDefault();
            }

            //判断用户是否有权限访问当前Action
            if (user!= null)
            {
                //如果有权限，继续执行Action
                base.OnActionExecuting(filterContext);
            }
            else
            {
                //如果没有权限，重定向到无权限页面（应为当前项目是MVC前后端完全分离，所以这里需要使用完全路径指向登录页面）
                filterContext.Result = new RedirectResult("http://127.0.0.1:8848/MvcWebUI/login.html");
                base.OnActionExecuting(filterContext);
            }
        }
        
    }
}